const express = require('express');
const multer = require('multer')
const fs = require('fs')
const path = require('path');
const bodyParser = require('body-parser');
const app = express()
const cors = require('cors')
const uploadDir = path.join(__dirname, '../upload')
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir)
}
app.use(cors())
app.use(express.json())
app.use(bodyParser.json())
//检查已上传的分片
app.post('/check', async (req, res) => {
  const { fileHash } = req.body
  console.log(fileHash);
  const fileChunkDir = path.join(uploadDir, fileHash)//分片目录
  if (fs.existsSync(fileChunkDir)) {
    return res.json([])//如果目录不存在，返回空数组
  }
  //返回已上传的分片索引
  const uploadedChunks = fs.readdirSync(fileChunkDir).map((chunk) =>
    parseInt(chunk.split("-"[1]))//提取分片索引
  )
  res.json(uploadedChunks)
})
//设置multer中间件、用于处理文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const fileHash = req.query.fileHash
    const fileChunkDir = path.join(uploadDir, fileHash)
    //确保切片目录存在
    if (!fs.existsSync(fileChunkDir)) {
      fs.mkdirSync(fileChunkDir, { recursive: true })
    }
    cb(null, fileChunkDir)
  },
  filename: function (req, file, cb) {
    const { chunkIndex } = req.query
    cb(null, `chunk-${chunkIndex}`)
  }
})
const upload = multer({ storage: storage })
//上传分片
app.post('/upload', upload.single('chunk'), (req, res) => {
  const { fileHash } = req.body
  res.status(200).send('上传成功')
})
//合并分片
app.post('/merge', async (req, res) => {
  const { fileHash, fileName, totalChunks } = req.body
  console.log("fileName", fileName);
  const fileChunkDir = path.join(uploadDir, fileHash)
  const filePath = path.join(uploadDir, fileName)
  //创建可写流用于最终合并文件
  const writeStream = fs.createWriteStream(filePath)
  for (let i = 0; i < totalChunks; i++) {
    const chunkPath = path.join(fileChunkDir, `chunk-${i}`)
    const data = fs.readFileSync(chunkPath)//读取分片
    writeStream.write(data)//写入最终文件
    //fs.unlinkSync(chunkPath) //删除分片
  }
  writeStream.end()//关闭流
  //fs.rmdirSync(fileChunkDir) //删除分片目录
  res.send('合并成功')
})
app.listen(3000, () => {
  console.log('server is running at port 3000')
})
